import { Component, OnInit } from '@angular/core';
import { NewsService } from '../../service/news.service';
import { Router, ActivatedRoute } from '@angular/router';
import { News } from '../../model/news';
import { ConfigService } from '../../service/config.service';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  parm:string;
  news:News;
  config:any;
  uploadurl:string;

  constructor(
    private newsservice:NewsService,
    private router:Router,
    private routerinfo:ActivatedRoute,
    private configserver:ConfigService
  ) {

    this.parm=this.routerinfo.snapshot.params["id"];

   }

  ngOnInit() {
    if(this.parm=='add'){
      this.news=new News();
      this.uploadurl=this.configserver.host+"/manage/ckeditorUpload"
      this.config={
        filebrowserImageUploadUrl:this.uploadurl,
        filebrowserUploadMethod : 'xhr',
        fileTools_requestHeaders : {
          'X-Requested-With': 'XMLHttpRequest',
          'Authorization':localStorage.getItem("token")
        }
      }
  
    }
    else{
      this.getSingleNews(this.parm);
    }
    


  }



  goBack(){

    this.router.navigate(['managelist']);

  }


  save(){
    if(this.parm=='add'){
      this.addNews();
    }
    else{
      this.updateNews();
    }

  }

  addNews(){
    console.dir(this.news);
    this.newsservice.addNews(this.news)
    .then((flag:boolean)=>{
      if(flag==true){
        this.goBack();
      }
      else{
        alert("添加异常，请刷新后重试");
      }
    })
  }


  updateNews(){
    this.newsservice.updateNews(this.news)
    .then((flag:boolean)=>{
      if(flag==true){
        this.goBack();
      }
      else{
        alert("添加异常，请刷新后重试");
      }
    })
  }


  getSingleNews(id:string){
    this.newsservice.getSingleNews(id)
    .then((data:News)=>{
      if(data){
        this.news=data;
      }
      else{
        alert("通讯异常，请刷新后重试")
      }
    })
  }


}
